import re
import os
from packages.ply import yacc
from filelist_parse.fl_lexer import lexer

class file_parse():
    def __init__(self):
        self.lexer = lexer()
        self.lexer.build()
        self.tokens = self.lexer.tokens
        self.parse = yacc.yacc(module=self)
        
        self.incdir  = []
        self.libext  = []
        self.libfile = []
        self.libdir  = []
        self.rtlfile = []

    def run(self,filelst):
        f = open(filelst,"r")
        text = f.read()
        return self.parse.parse(text,lexer=self.lexer)

    def p_error(self,p):
        while 1:
            tok = self.parse.token()
            if not tok:
                break

    def p_filelist(self,p):
        """ filelist : COMMENT
                     | incdir   
                     | libext
                     | libfile
                     | libdir
                     | rtlfile
                     | rtllist
                     | filelist COMMENT
                     | filelist incdir
                     | filelist libext
                     | filelist libfile
                     | filelist libdir
                     | filelist rtlfile
                     | filelist rtllist """
        pass
    
    def p_incdir(self,p):
        """ incdir : INCDIR """
        incdir = p[1].split("+")
        for i in incdir:
            if(i not in self.incdir):
                self.incdir.append(i)

    def p_libext(self,p):
        """ libext : LIBEXT """
        libext = p[1].split("+")
        for i in libext:
            if(i not in self.libext):
                self.libext.append(i)

    def p_libfile(self,p):
        """ libfile : LIBFILE """
        self.libfile.append(p[1])

    def p_libdir(self,p):
        """ libdir : LIBDIR """
        self.libdir.append(p[1])

    def p_rtlfile(self,p):
        """ rtlfile : RTLFILE """
        file = p[1]
        file = self.__env_replace__(file)

        if os.path.exists(file):
            self.rtlfile.append(file)


    def p_rtllist(self,p):
        """ rtllist : RTLLIST """
        filelist = p[1]

        filelist = self.__env_replace__(filelist)

        p = file_parse()
        p.run(filelist)
        
        self.incdir.extend(p.incdir)
        self.libfile.extend(p.libfile)
        self.libdir.extend(p.libdir)
        self.rtlfile.extend(p.rtlfile)
        for i in p.libext:
            if(i not in self.libext):
                self.libext.append(i)

    def getlist(self):
        return self.rtlfile+self.libfile
    
    def __env_replace__(self,string):
        if re.search("\$",string):
            string = re.sub("\$[({]?(\w+)[)}]?",lambda m:os.environ.get(m.group(1)),string)
        return string
        

if __name__ == "__main__":
    p = file_parse()
    p.run("test.lst")

    print(p.rtlfile)
